#include "sspHandle.hpp"

sspHandle::sspHandle(imf::SspClient* ptr) : clientPtr(ptr),saver(nullptr)
{
  decode.reset(new h264decode_gst);
  //初始化一下
  clientPtr->init();
  clientPtr->setOnH264DataCallback(std::bind(&sspHandle::H264DataCallback,this,std::placeholders::_1));
  clientPtr->setOnMetaCallback(std::bind(&sspHandle::MetaDataCallback,this,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3));
  clientPtr->setOnAudioDataCallback(std::bind(&sspHandle::AudioDataCallback,this,std::placeholders::_1));
  clientPtr->setOnDisconnectedCallback(std::bind(&sspHandle::DisconnectCallback,this));
  threadID=pthread_self();

  workThread=std::jthread(&sspHandle::threadFunc_dataReceive,this);
}

sspHandle::~sspHandle()
{
  if(threadID!=pthread_self())
    pthread_cancel(threadID);
  delete clientPtr;
  decode.reset(nullptr);
  workThread.request_stop();
  if(workThread.joinable())
    workThread.join();
}

void sspHandle::SetNewImageCallback(std::function<void(ImageType)> func)
{
  funcNewImageEvent=func;
}

void sspHandle::H264DataCallback(struct imf::SspH264Data * h264)
{
  //判断相机是否重新开始采集
  if(lastFrameID>h264->frm_no)
    decode.reset(new h264decode_gst);
  lastFrameID=h264->frm_no;
  //decode->h264decode(h264->data,h264->len,FramePara,RGBData,nullptr);
  decode->InputNewImage(h264->data,h264->len,h264->frm_no);
  if(saver!=nullptr)
    saver->InputH264((const char*)h264->data,h264->len);
}

void sspHandle::MetaDataCallback(struct imf::SspVideoMeta * v,struct imf::SspAudioMeta * a,struct imf::SspMeta * m)
{
  imgHeight=v->height;
  imgWidth=v->width;
}

void sspHandle::DisconnectCallback()
{
  DisconnectEvent();
}

void sspHandle::AudioDataCallback(struct imf::SspAudioData * data)
{

}

void sspHandle::Start()
{
  clientPtr->start();
}

void sspHandle::Stop()
{
  clientPtr->stop();
}

void sspHandle::threadFunc_dataReceive(std::stop_token stoken)
{
  threadID=pthread_self();
  while(!stoken.stop_requested())
  {
    //如果没有新的内容就会堵塞
    funcNewImageEvent(decode->GetNewImage());
  }
}

void sspHandle::StartRecord(const std::string & filePath)
{
  saver.reset(new H264Save(filePath));
}

void sspHandle::StopRecord()
{
  saver.reset(nullptr);
}

